package com.alipay.rebate.shop.scheduler.orderimport;

import com.alipay.rebate.shop.constants.LuckyMonCouponConstant;
import com.alipay.rebate.shop.constants.OrdersConstant;
import com.alipay.rebate.shop.model.CommissionFreezeLevelSettings;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.model.UserIncome;
import com.alipay.rebate.shop.pojo.user.customer.UserCouponRsp;
import java.math.BigDecimal;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

@Component
public class AcOrdersImporter extends AbstractOrdersImporter{

  private Logger logger = LoggerFactory.getLogger(AcOrdersImporter.class);
  @Autowired
  DataSourceTransactionManager dataSourceTransactionManager;
  @Autowired
  TransactionDefinition transactionDefinition;
  @Override
  void doDealWithOrder(Orders orders, Orders previousOrder, Long parentUserId, Long parentPUserId,
      User user, User oneLevelUser) {
    TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
    try {
      // 如果先前数据库没有订单，那么用户相应订单数加1
      if(previousOrder == null){
        countUserOrdersNum(orders);
      }

      // 查看是否是第一单完成订单,如果是,进行新人任务奖励
      // 以前没有完成的订单, 这笔订单已经到了结算/完成状态
      if(orders.getUserId() != null) {
        checkNewUserTask(user.getUserId(), orders);
      }

      // 根据状态获取到实际能拿到的所有佣金
      BigDecimal totalGetMoney = getTotalGetMoney(orders);
      logger.debug("Done totalGetMoney is : {}", totalGetMoney);

      // 如果是活动订单
      dealwithActivityOrdersLogicIfis(previousOrder,orders,user.getUserId());

      // 订单付款状态
      // 计算用户佣金，用户上级佣金，上上级佣金，上上上级佣金
      countCommission(totalGetMoney,orders,parentUserId, parentPUserId,user,oneLevelUser);

      // 如果数据库有记录，那么更新订单信息，没有则直接插入
      saveOrUpdateOrders(orders,previousOrder);

      // 获取冻结配置，根据冻结配置决定是否冻结
      CommissionFreezeLevelSettings freezeCommissionSettings = getFreezeSettingsByMoney(orders.getUserCommission());
      logger.debug("CommissionFreezeLevelSettings is : {}",freezeCommissionSettings);

      // 创建收益记录
      createIncomeRecord(orders, user.getUserId(), parentUserId,
          parentPUserId,previousOrder,freezeCommissionSettings);

      // 不冻结的话直接增加用户集分宝
      if(freezeCommissionSettings == null){
        userHelper.plusUserUit(orders,previousOrder,user,oneLevelUser);
      }

      // 拉新奖励
      if(previousOrder == null || OrdersConstant.PAID_STATUS.equals(previousOrder.getTkStatus())){
        checkAndAwardToUser(orders);
      }

      // 红包奖励
      giveLuckyMoney(user);

      dataSourceTransactionManager.commit(transactionStatus);

    }catch (Exception ex){
      logger.error("accountOrders Exception is : {} ",ex);
      dataSourceTransactionManager.rollback(transactionStatus);
    }

  }

  @Override
  protected void createIncomeRecord(Orders orders, Long userId, Long parentUserId,
      Long parentPuserId, Orders previousOrders,
      CommissionFreezeLevelSettings freezeCommissionSettings) {
    if(previousOrders == null){
      logger.debug("insert userIncome record");
      insertUserIncome(orders,userId,parentUserId,parentPuserId,freezeCommissionSettings);
    }else{
      // 查询数据库是否已经有用户记录
      List<UserIncome> userIncomeList = userIncomeMapper
          .selectUserIncomeByOrdersId(orders.getTradeId());
      // 如果数据库有记录，那么就更新住居
      if (userIncomeList.size() > 0) {
        // 如果数据库有记录，那么就更新住居
        logger.debug("orders is : {}",orders.getTradeId());
        updateUserIncome(orders, userId, parentUserId, parentPuserId,
                userIncomeList, orders.getTkStatus(), freezeCommissionSettings);
      }else{
        insertUserIncome(orders,userId,parentUserId,parentPuserId,freezeCommissionSettings);
      }
    }
  }

  private void giveLuckyMoney(User user){
    List<UserCouponRsp> userCouponRsps = couponGetRecordMapper.selectCouponDetailByUserId(user.getUserId());
    luckyMoneyHelper.openLuckyMoneyCouponIfNeed(user.getUserId(),
        LuckyMonCouponConstant.CONDITION_TYPE_ORDER_REWARD,
        userCouponRsps,true);
    luckyMoneyHelper.openLuckyMoneyCouponIfNeed(user.getUserId(),
        LuckyMonCouponConstant.CONDITION_TYPE_PAID_MONEY,
        userCouponRsps,true);
  }

}
